package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpRseponse;
import com.webserver.vo.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 用来处理注册业务
 */
public class RegServlet {
    static{
        File userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }
    public void service(HttpRequest request, HttpRseponse rseponse){
        System.out.println("RegServlet:开始处理注册...");
        //1获取注册页面上表单提交上来数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        HttpRseponse response;
        if(username==null||password==null||nickname==null||
                ageStr==null||!ageStr.matches("[0-9]+")){
            File file = new File("./webapps/myweb/reg_input_error.html");
            rseponse.setEntity(file);
            return;
        }
        /*
            判断该用户是否已经存在，若存在则直接响应页面:have_user.html
            剧中显示一行字:该用户已存在，请重新注册。

             都满足才执行下面的注册操作
         */
        File userFile = new File("./users/"+username+".obj");
        if(userFile.exists()){
            File file = new File("./webapps/myweb/have_user.html");
            rseponse.setEntity(file);
            return;
        }



        int age = Integer.parseInt(ageStr);
        //2将用户信息写入文件保存
        User user = new User(username,password,nickname,age);

        try(
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);

            //设置response响应注册成功页面
            File file = new File("./webapps/myweb/reg_success.html");
            rseponse.setEntity(file);


        }catch(IOException e){
            e.printStackTrace();
        }



        //3设置response注册成功页面




        System.out.println("RegServlet:注册完毕");
    }
}
